﻿using Prism.Events;
using Prism.Regions;
using Prism.Services.Dialogs;
using SharpDX;
using SmartPlant.Core;
using SmartPlant.Core.Mvvm;
using SmartPlant.Model;
using SmartPlant.Modules.Base.Views;
using SmartPlant.Services.Interfaces;
using SmartPlant.WinCore;
using SmartPlant.WinCore.Helper;
using System.IO;
using System.Windows.Input;
using Telerik.Windows.Controls;
using Telerik.Windows.Documents.Spreadsheet.FormatProviders.OpenXml.Xlsx;
using Telerik.Windows.Documents.Spreadsheet.Model;
using Telerik.Windows.Persistence.Core;
using Unity;

namespace SmartPlant.Modules.Base.ViewModels
{
    public class SpecEditViewModel : RegionViewModelBase
    {
        private readonly IEventAggregator _eventAggregator;
        private readonly ISpecSheetDataService _InsServ;

        public string CmpntID { get; set; }
        public string DwgId { get; set; }
        private Workbook workbook = new Workbook();
        public Workbook Workbook
        {
            get
            {
                return this.workbook;
            }
            set
            {
                if (this.workbook != value)
                {
                    this.workbook = value;
                    RaisePropertyChanged();
                }
            }
        }
        //public bool TestMode { get; set; }
        private Prism.Commands.DelegateCommand<object> _RevisionManagerCommand;
        public ICommand RevisionManagerCommand { get
            {
                if(_RevisionManagerCommand != null) return _RevisionManagerCommand;
                _RevisionManagerCommand = new Prism.Commands.DelegateCommand<object>(onRevisionManager);
                     return _RevisionManagerCommand;
            } }
        public ICommand RefreshCommand { get; set; }
        public ICommand SaveCommand { get; set; }
        public SpecEditViewModel(
            IRegionManager regionManager,
            IDialogService dialog,
            IUnityContainer unityContainer,
            IEventAggregator eventAggregator,
            ISpecSheetDataService achievementService,
            IImportUtilityService importUtilityService)
           : base(regionManager, unityContainer, dialog)
        {
            _eventAggregator = eventAggregator;
            _InsServ = achievementService;
            
            this.RefreshCommand = new DelegateCommand(onRefreshCommand);
            this.SaveCommand = new DelegateCommand(onSaveCommand);
            // _eventAggregator.GetEvent<CompSelectedEvent>().Subscribe(OnCompSelectedEvent);
        }
        /// <summary>
        /// 没啥必要
        /// </summary>
        /// <param name="treeNode"></param>
        //private async void OnCompSelectedEvent(ITreeNodeModel treeNode)
        //{
        //    CmpntID = treeNode.Id;
        //    await SpecOut();
        //}

        //控制是否可以多开
        public override bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return false;
        }
        public override async void OnNavigatedTo(NavigationContext navigationContext)
        {
            if (navigationContext.Parameters.ContainsKey(DialogParameterKeys.Title))
                Title.TitleText = navigationContext.Parameters[DialogParameterKeys.Title].ToString();
            if (navigationContext.Parameters.ContainsKey(DialogParameterKeys.Id))
                CmpntID = navigationContext.Parameters[DialogParameterKeys.Id].ToString();
            if (navigationContext.Parameters.ContainsKey("Dwgid"))
                DwgId = navigationContext.Parameters["Dwgid"].ToString();
            if (navigationContext.Parameters.ContainsKey(DialogParameterKeys.Content))
            {
                var excelContent = navigationContext.Parameters[DialogParameterKeys.Content] as FileContentResultBaseString;
                var bytes = Convert.FromBase64String(excelContent.Data);//server端正好是用的ToBase64String，把byte[]变为的string
                var memoryStream = new MemoryStream(bytes);
                //return new RESTfulResult<Stream> { data = memoryStream, succeeded = true };

                memoryStream.Position = 0;
                var length = memoryStream.Length;
                var buffer = new byte[length];
                memoryStream.Read(buffer, 0, (int)length);
                XlsxFormatProvider formatProvider = new XlsxFormatProvider();
                Workbook = formatProvider.Import(buffer);
            }
            else
            {
                Workbook = new Workbook();
            }

        }
        //protected override async void OnInitPage(object obj)
        //{
        //    //ProjectID = GlobalObject.CurrentProject.ProjId.ToString();
        //    //CmpntID = GlobalObject.CurrentCmpntID;
        //    //if (string.IsNullOrEmpty(CmpntID))
        //    //{
        //    //    return;
        //    //}
        //    //else
        //    //{
        //    //    await SpecOut();
        //    //}


        //}
        ///// <summary>
        ///// 展示
        ///// </summary>
        ///// <returns></returns>
        //async Task SpecOut()
        //{
        //    if (!string.IsNullOrEmpty(CmpntID))
        //    {
        //        try
        //        {
        //            var rr = await _InsServ.DownSpecOutputAsync(ProjectID, CmpntID);
        //            if (!rr.succeeded)
        //            {
        //                switch (rr.statusCode)
        //                {
        //                    case 400:
        //                    case 500:
        //                        //业务
        //                        Dialog.ShowAltert(rr.msg);
        //                        //关闭view

        //                        break;
        //                    default:
        //                        LoggerHelper.Current.Error(rr.errors.ToString());
        //                        break;
        //                }

        //            }
        //            else
        //            {
        //                var bytes = Convert.FromBase64String(result.data.Data);//server端正好是用的ToBase64String，把byte[]变为的string
        //                var memoryStream = new MemoryStream(bytes);
        //                return new RESTfulResult<Stream> { data = memoryStream, succeeded = true };
        //            }
        //            rr.data.Position = 0;
        //            var length = rr.data.Length;
        //            var buffer = new byte[length];
        //            rr.data.Read(buffer, 0, (int)length);
        //            XlsxFormatProvider formatProvider = new XlsxFormatProvider();
        //            Workbook = formatProvider.Import(buffer);
        //        }
        //        catch (Exception x)
        //        {
        //            var xMessage = $"数据加载失败：{x.Message}！！！";
        //            LoggerHelper.Current.Error(xMessage, x);
        //        }
        //    }
        //    else
        //    {
        //        Workbook = new Workbook();
        //    }
        //}
        private void onRefreshCommand(object obj)
        { }
        private void onRevisionManager(object obj) 
        {
            Prism.Services.Dialogs.DialogParameters dialogParameters = new Prism.Services.Dialogs.DialogParameters();
            dialogParameters.Add(DialogParameterKeys.Id, DwgId);
            Dialog.ShowDialog(nameof(RevisionManager), dialogParameters, null);
        }    
        private async void onSaveCommand(object obj)
        {
            try
            {
                XlsxFormatProvider formatProvider = new XlsxFormatProvider();
                if (!string.IsNullOrEmpty(CmpntID))
                {

                    var buffer = formatProvider.Export(workbook);

                    var files = new List<NetworkFileInfo> { new NetworkFileInfo { FileName = "spec.xlsx", Data = buffer } };
                    var blankValueUpdteFlag = true;
                    var RES = await _InsServ.UploadSpecInputAsync(files, GlobalObject.CurrentProject.ProjId.ToString(), GlobalObject.CurrentProject.ProjName.ToString(), CmpntID, blankValueUpdteFlag);
                    if (!RES.succeeded)
                    {
                        switch (RES.statusCode)
                        {
                            case 400:
                            case 500:
                                //业务错误
                                Dialog.ShowAltert(RES.errors);
                                //关闭view
                                break;
                            default:
                                //网络错误
                                Dialog.ShowAltert(RES.errors);
                                LoggerHelper.Current.Error(RES.errors);
                                break;
                        }
                        return;
                    }
                    else
                    {
                        var bytes = Convert.FromBase64String(RES.data.Data);//server端正好是用的ToBase64String，把byte[]变为的string
                        var memoryStream = new MemoryStream(bytes);
                        //return new RESTfulResult<Stream> { data = memoryStream, succeeded = true };

                        memoryStream.Position = 0;
                        var length = memoryStream.Length;
                        var buffer2 = new byte[length];
                        memoryStream.Read(buffer2, 0, (int)length);   
                        Dialog.ShowMessage("保存成功！");
                        formatProvider = new XlsxFormatProvider();
                        Workbook = formatProvider.Import(buffer2);
                        //SpecInputModels.Clear();
                     
                    }
                }

            }
            catch (Exception x)
            {
                string msg = $"保存失败：{x.Message}";
                LoggerHelper.Current.Error(msg, x);
            }
        }
    }
}
